from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from .services import OrderService, SearchService
from .exceptions import (
    InvalidOrderException,
    InsufficientStockException,
    ProductNotFoundException
)
import json
import logging

logger = logging.getLogger(__name__)


@csrf_exempt
@require_http_methods(["POST"])
def create_order(request):
    """批量订单处理视图"""
    try:
        data = json.loads(request.body)
        if not data.get('items'):
            raise InvalidOrderException("订单项不能为空")

        # 调用服务层处理
        results = OrderService.process_batch_order(
            user_id=request.user.id,
            items=data['items']
        )

        return JsonResponse({
            'success': True,
            'data': results,
            'message': '订单处理完成'
        })

    except InvalidOrderException as e:
        logger.warning(f"订单格式错误: {str(e)}")
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=400)

    except Exception as e:
        logger.error(f"订单创建异常: {str(e)}", exc_info=True)
        return JsonResponse({
            'success': False,
            'error': '系统繁忙，请稍后重试'
        }, status=500)


@require_http_methods(["GET"])
def product_search(request):
    """商品搜索视图"""
    try:
        keyword = request.GET.get('q', '').strip()
        if not keyword:
            raise ValueError("搜索关键词不能为空")

        # 调用服务层处理
        products = SearchService.search_by_keyword(keyword)

        return JsonResponse({
            'success': True,
            'data': products,
            'count': len(products)
        })

    except ValueError as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=400)

    except Exception as e:
        logger.error(f"搜索异常: {str(e)}", exc_info=True)
        return JsonResponse({
            'success': False,
            'error': '搜索服务暂不可用'
        }, status=500)


@require_http_methods(["GET"])
def product_detail(request, product_id):
    """商品详情视图（带缓存）"""
    try:
        product = SearchService.get_product_with_cache(product_id)
        return JsonResponse({
            'success': True,
            'data': product
        })
    except ProductNotFoundException:
        return JsonResponse({
            'success': False,
            'error': '商品不存在'
        }, status=404)
    except Exception as e:
        logger.error(f"商品详情获取失败: {str(e)}")
        return JsonResponse({
            'success': False,
            'error': '获取商品信息失败'
        }, status=500)
